<template>
	<div class="addBox">
		<div class="addBoxTop">
			<span class="font_size20">签到规则</span>
		</div>
		<div class="addDiv" v-loading="sLoading">
			<el-form ref="form" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择"
						:disabled="(isDisabled || isDisbableInfo.type) && isEdit">
						<el-option v-for="item in getYunShopsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="规则名称" prop="title" v-if="objectForm.title">
					<el-input v-model="objectForm.title" class="input-w" placeholder="请填写规则名称" show-word-limit
						:disabled="(isDisabled || isDisbableInfo.type) && isEdit"></el-input>
				</el-form-item>
				<el-form-item :label="'签到提醒'" prop="remind">
					<div class="switchDiv">
						<el-switch v-model="objectForm.valueRemind"
							:disabled="(isDisabled || isDisbableInfo.type) && isEdit"></el-switch>
					</div>
				</el-form-item>
				<el-form-item :label="'提醒时间'" prop="remind_t">
					<el-select v-model="objectForm.remind_t" placeholder="请选择"
						:disabled="(isDisabled || isDisbableInfo.type) && isEdit">
						<el-option v-for="item in t_ls" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="签到周期" prop="cycle">
					<el-select v-model="objectForm.cycle" placeholder="请选择"
						:disabled="(isDisabled || isDisbableInfo.type) && isEdit">
						<el-option v-for="item in zq_ls" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="连续签到" prop="r_ls_value">
					<div class="switchDiv">
						<el-switch v-model="objectForm.r_ls_value" @change="handler_r_ls"
							:disabled="(isDisabled || isDisbableInfo.type) && isEdit"></el-switch>
					</div>
					<div class="sign-box" v-if="objectForm.r_ls_value">
						<div class="flex_between mb20" v-for="(item, imIndex) in objectForm.r_ls" :key="item.id">
							<div class="label-box flex_between">
								<div>
									<span class="mr10">签到天数</span>
									<el-input-number v-model="item.days" controls-position="right" :min="0" :max="99999"
										:precision="0" :disabled="(isDisabled || isDisbableInfo.type) && isEdit"
										class="el-input-xnumber-box"></el-input-number>
								</div>
								<div>
									<span class="mr10">赠送数量</span>
									<el-input-number v-model="item.v" controls-position="right" :min="0" :max="99999"
										:precision="0" :disabled="(isDisabled || isDisbableInfo.type) && isEdit"
										class="el-input-xnumber-box"></el-input-number>
									<span class="tip-text">(积分)</span>
								</div>
								<div>
									<span class="mr10">赠送次数</span>
									<el-select v-model="item.do_ch" placeholder="请选择"
										:disabled="(isDisabled || isDisbableInfo.type) && isEdit" style="width: 150px;">
										<el-option v-for="item in do_ls" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
								</div>
								<div class="object-item-delete-box" @click="!isDisabled && deleteObject(imIndex)"
									v-if="!((isDisabled || isDisbableInfo.type) && isEdit)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object ml20">
								<el-button type="primary" v-if="objectForm.r_ls.length - 1 == imIndex"
									@click="addObject" icon="el-icon-plus" circle
									:disabled="((isDisabled || isDisbableInfo.type) && isEdit)"></el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="累计签单" prop="r2_ls_value">
					<div class="switchDiv">
						<el-switch v-model="objectForm.r2_ls_value" @change="handler_r2_ls"
							:disabled="(isDisabled || isDisbableInfo.type) && isEdit"></el-switch>
					</div>
					<div class="sign-box" v-if="objectForm.r2_ls_value">
						<div class="flex_between mb20" v-for="(item, imIndex) in objectForm.r2_ls" :key="item.id">
							<div class="label-box flex_between">
								<div>
									<span class="mr10">签到天数</span>
									<el-input-number v-model="item.days" controls-position="right" :min="0" :max="99999"
										:precision="0" :disabled="(isDisabled || isDisbableInfo.type) && isEdit"
										class="el-input-xnumber-box"></el-input-number>
								</div>
								<div>
									<span class="mr10">赠送数量</span>
									<el-input-number v-model="item.v" controls-position="right" :min="0" :max="99999"
										:precision="0" :disabled="(isDisabled || isDisbableInfo.type) && isEdit"
										class="el-input-xnumber-box"></el-input-number>
									<span class="tip-text">(积分)</span>
								</div>
								<div>
									<span class="mr10">赠送次数</span>
									<el-select v-model="item.do_ch" placeholder="请选择"
										:disabled="(isDisabled || isDisbableInfo.type) && isEdit" style="width: 150px;">
										<el-option v-for="item in do_ls" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
								</div>
								<div class="object-item-delete-box" @click="!isDisabled && deleteObject(imIndex)"
									v-if="!((isDisabled || isDisbableInfo.type) && isEdit)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object ml20">
								<el-button type="primary" v-if="objectForm.r_ls.length - 1 == imIndex"
									@click="addObject" icon="el-icon-plus" circle
									:disabled="((isDisabled || isDisbableInfo.type) && isEdit)"></el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="规则">
					<el-input type="textarea" v-model="objectForm.txt_rule" class="input-w" placeholder="请填写活动规则"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="启用" prop="value1">
					<div class="switchDiv">
						<el-switch v-model="objectForm.value1"
							:disabled="(isDisabled || isDisbableInfo.type) && isEdit"></el-switch>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="addDivBtn">
			<div class="acvite-btn" v-if="btnShow" @click="createActivity">提交</div>
			<div class="acvite-btn" v-if="objectForm.status == 2 && isEdit" @click="stopActivity">停止</div>
			<div class="acvite-btn" v-if="editShow && isEdit" @click="editActivity">编辑</div>
			<template v-if="!isEdit">
				<div class="acvite-btn" @click="createActivity">提交</div>
				<div class="back-btn" @click="clearForm">取消</div>
			</template>
			<div class="back-btn" @click="goBack" v-if="objectForm.act == 'add'">返回</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, defineExpose } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { priceInput } from '@/utils/common.js'
import { fractTypeList, ptypeList } from '@/utils/dict.js'
import util from '@/js/util/Util.js'

// 获取当前组件实例
const { proxy } = getCurrentInstance()
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => [],
	},
	typeLsSys: {
		type: Array,
		default: () => [],
	},
	detailID: {
		type: String,
		default: "",
	},
	// 如果是编辑页面，设置某些值不能编辑
	isDisbableInfo: {
		type: Object,
		default: () => ({
			type: false,
		}),
	},
})

const emit = defineEmits(['addTpBmFun'])
const form = ref(null)
const sLoading = ref(false)
const isEdit = ref(true)

const objectForm = ref({
	act: "add",
	id: "",
	title: "",
	shopid_yd: "",
	cycle: "1", // 结算周期 1 不限 2 每周末 3 每月末 默认1
	txt_rule: "", // 活动规则
	r_ls: [], // 格式--连续签到 修复：id改为字符串
	r_ls_value: false,
	r2_ls: [], // 格式--累计签到 修复：id改为字符串
	r2_ls_value: false,
	status: '', // 启用
	day_f: '', // 规则生效起始日期；格式 =2022-01-01
	remind: 1, // 是否提醒1是2否  默认1
	valueRemind: true, // 是否提醒
	remind_t: '', // 提醒时间；格式如12:00   remind =1 时必填 remind =2 时 无效
	value1: true, // 启用
})

const btnShow = computed(() => {
	return (objectForm.value.status == 1 || objectForm.value.act == 'add') && (props.isDisbableInfo.index_key == '-1')
})

const editShow = computed(() => {
	return objectForm.value.status == 2 && (props.isDisbableInfo.index_key == '-1')
})

// 添加计算属性
const isDisabled = computed(() => {
	const disabledStatus = ['2', '3']
	return (disabledStatus.includes(objectForm.value.status))
})

const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	remind_t: [
		{ required: true, message: '请选择提醒时间', trigger: 'change' }
	],
})

const handler_r_ls = (e) => {
	if (objectForm.value.r_ls_value) {
		// 只有当数组为空时才初始化默认数据
		if (!objectForm.value.r_ls || objectForm.value.r_ls.length === 0) {
			objectForm.value.r_ls = [{ id: util.uuid(), days: 0, do_ch: '1', v: 0 }]
		}
	}
}

const handler_r2_ls = () => {
	if (objectForm.value.r2_ls_value) {
		// 只有当数组为空时才初始化默认数据
		if (!objectForm.value.r2_ls || objectForm.value.r2_ls.length === 0) {
			objectForm.value.r2_ls = [{ id: util.uuid(), days: 0, do_ch: '1', v: 0 }]
		}
	}
}

const getYunShopsList = computed(() => {
	return props.getYunShopList
})

const restFun = () => {
	// 重置为默认值
	objectForm.value = {
		act: "add",
		id: "",
		title: "",
		shopid_yd: "",
		cycle: "1",
		txt_rule: "",
		r_ls: [],
		r_ls_value: false,
		r2_ls: [],
		r2_ls_value: false,
		status: '',
		day_f: '',
		remind: 1,
		valueRemind: true,
		remind_t: '',
		value1: true,
	};
	form.value?.resetFields();
	console.log("objectForm.value.title=", objectForm.value.title)
}

const submitForm = async () => {
	const valid = await form.value?.validate()
	if (valid) {
		const params = {
			...objectForm.value,
			status: objectForm.value.value1 ? 2 : 1,
		}
		if (params.r_ls.length == 0 && params.r2_ls.length == 0) {
			proxy.$message.error('至少添加一种规则')
			return
		}
		if (!params.r_ls_value) {
			params.r_ls = []
		}
		if (!params.r2_ls_value) {
			params.r2_ls = []
		}
		const res = await proxy.$api({ url: config.yx_qd_event_save, data: params })
		if (res.status == 1) {
			proxy.$message.success(res?.msg || '操作成功')
			isEdit.value = true
			emit("addTpBmFun", {
				type: objectForm.value.act,
				status:'-1',
			})
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	}
}

const createActivity = () => {
	submitForm("form")
}

const stopActivity = async () => {
	proxy.$confirm(`此操作将停止【${objectForm.value.title}】规则, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		let params = {
			...objectForm.value,
			act: 'stop',
			status: 3,
		}
		let res = await proxy.$api({ url: config.yx_qd_event_save, data: params });
		if (res.status == 1) {
			proxy.$message({
				message: '停止成功',
				type: 'success'
			});
			emit("addTpBmFun", {
				type: 'del',
				status: '-1',
			})
		} else {
			proxy.$message({
				message: res?.msg || '停止失败',
				type: 'error'
			})
		}
	})
}

const editActivity = () => {
	isEdit.value = false
}

const clearForm = () => {
	isEdit.value = true
}

const goBack = () => {
	emit("backFun", 'back')
}

// 获取详情
const getDetail = async () => {
	sLoading.value = true
	const res = await proxy.$api({ url: config.yx_qd_event_info, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	if (res.status === 1 && res.data) {
		const data = res.data
		objectForm.value.id = data.id;
		objectForm.value = {
			...data,
			r_ls: data.r_ls || [],
			r2_ls: data.r2_ls || [],
			r_ls_value: data?.r_ls?.length > 0,
			r2_ls_value: data?.r2_ls?.length > 0,
			remind_t: data.remind_t || '',
			value1: data.status == 2 ? true : false,
			act: 'edt',
		}
		console.log("objectForm.value=", objectForm.value)
	}
}
const t_ls = ref([])
const zq_ls = ref([])
const getTimeLs = async () => {
	const res = await proxy.$api({ url: config.yx_qd_time_ls, data: { evenid: props.detailID } })
	if (res.status === 1 && res.data) {
		let result = res.data
		zq_ls.value = result.zq_ls.map(item => {
			return {
				...item,
				name: item.title,
				id: item.id,
			}
		})
		t_ls.value = result.t_ls.map(item => {
			return {
				...item,
				name: item.time_f1,
				id: item.time_f1,
			}
		})
	}
}
getTimeLs()

// 实现添加数组元素的方法
const addObject = () => {
	objectForm.value.r_ls.push({
		id: util.uuid.toString(), // 修复：确保id是字符串
		days: 0,  // 默认天数为1
		do_ch: '1', // 默认类型
		v: 0      // 默认赠送积分
	});
};

// 实现删除数组元素的方法
const deleteObject = (index) => {
	if (objectForm.value.r_ls && objectForm.value.r_ls.length > 0) {
		// 确认删除
		proxy.$confirm('确定要删除这条数据吗?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			// 从数组中删除指定索引的元素
			objectForm.value.r_ls.splice(index, 1);
			proxy.$message.success('删除成功');
		}).catch(() => {
			// 取消删除
			proxy.$message.info('已取消删除');
		});
	}
};

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			form.value?.resetFields()
		}
		if (!newVal) {
			restFun()
		}
		isEdit.value = true
	}, 200)
}, { immediate: true })

watch(() => objectForm.value.valueRemind, (newVal) => {
	if (newVal) {
		objectRules.value.remind_t[0].required = true
	} else {
		objectRules.value.remind_t[0].required = false
	}
}, { immediate: true, deep: true })

watch(() => objectForm.value.valueRemind, (newVal) => {
	if (newVal) {
		objectForm.value.remind = 1
	} else {
		objectForm.value.remind = 2
	}
}, { immediate: true, deep: true })

onMounted(() => { })


const do_ls = ref([
	{
		id: '1',
		name: '一次性',
	},
	{
		id: '2',
		name: '重复',
	},
])

defineExpose({
	restFun,
	objectForm
})

</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;

			span {
				margin-right: 20px;
			}
		}

		.timeShowBox {
			// width: 600px;
			height: 40px;
			border: 1px solid #DCDFE6;
			border-radius: 5px;
			cursor: pointer;

			.timeShowdiv {
				padding: 0 10px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;

				span {
					margin-right: 10px;

					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}

	::v-deep.mb-box {
		margin-bottom: 10px;

		&:last-child {
			margin: 0;
		}

		.el-radio__label {
			display: none;
		}

		.pl-box {
			font-size: 14px;
			margin-bottom: 10px;
			display: flex;
			align-items: center;
			cursor: pointer;

			span {
				margin-right: 10px;
			}

			img {
				margin-right: 10px;
				width: 25px;
				height: 25px;
			}

			.txt-box {
				width: 145px;
				display: flex;
				align-items: center;
			}
		}

		.color-box {
			display: flex;
			font-size: 14px;

			.color-row {
				margin-right: 10px;
				text-align: center;
				cursor: pointer;

				.color-title {
					font-size: 12px;
					margin: 10px 0;
				}

				.background-item {
					width: 80px;
					height: 80px;
				}
			}
		}
	}
}

.tip-text {
	font-size: 12px;
	color: #666;
	margin-left: 10px;
}

.switch-mode {
	color: #3388ff;
	cursor: pointer;
}

.disabled-btn {
	opacity: 0.5;
	cursor: not-allowed;
	pointer-events: none;
}

.acvite-btn {
	opacity: 1;
	cursor: pointer;
}

.sign-box {
	border: 1px solid #DCDFE6;
	border-radius: 6px;
	padding: 20px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.label-box {
	position: relative;
	flex: 1;
	box-sizing: border-box;
	height: 80px;
	padding: 10px 30px 10px;
	border: 1px solid #DCDFE6;
	border-radius: 6px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-direction: row;
	gap: 10px;
	position: relative;

	.object-item-delete-box {
		position: absolute;
		right: 0;
		top: 0;
		cursor: pointer;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.1);
		border-bottom-left-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
		font-size: 12px;

		&:hover {
			background: rgba(0, 0, 0, 0.3);
		}
	}
}

.add-object {
	width: 44px;
}

::v-deep .el-color-picker__color {
	border: none !important;
}

::v-deep .el-color-picker__color-inner {
	border: none !important;
}

::v-deep .el-color-picker__mask {
	display: none !important;
}

::v-deep .el-icon-close:before {
	content: "\e6df";
}

::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
	background-color: #fcfcfc !important;
	color: #666 !important;
	border-color: #f1f1f1 !important;
}

::v-deep .el-input-xnumber-box {
	width: 150px !important;

	.el-input__inner {
		text-align: left !important;
	}
}
</style>
